import { getCategory } from '@/api/products';
import { ref, computed } from 'vue'
import { useRequest } from 'vue-request';
//hooks:提高代码复用性


export const useCategory = () => {
    // const categoryTree = ref([]);
    // const loading = ref(false);
    // const _getCategory = async () => {
    //     loading.value = true;
    //     categoryTree.value = await getCategory().then(res => res.data.data);
    //     loading.value = false
    // }
    // _getCategory()

    //{data:categoryTree}重命名
    const {data:categoryTree,loading} = useRequest(getCategory,{
        cacheKey:'category',
        staleTime:2*60*1000  //2min
    });





    //树转列表->map
    function treeToList(tree, result = [], parent = null) {
        tree.forEach(element => {
            //浅拷贝，防止影响源数据
            const item = { ...element }
            //添加parentId属性
            item.parentId = parent

            result.push(item)
            //查看有没子节点
            if (item.children) {
                treeToList(item.children, result, item.id);
            }
            //删除
            delete item.children
        });

        return result;
    }
    //树转列表
    const categoryList = computed(() => treeToList(categoryTree.value))
    //转哈希表
    const categoryMap = computed(() => categoryList.value.reduce((prev, curr) => ((prev[curr.id] = curr), prev), {}))

    /* 
        {
            1: {has_children:true
                id:1
                level:0
                    name:"手机"
                parentId:null},
            3: {
                has_children:false
                id:3
                level:2
                name:"高端手机"
                parentId:2
            },
            2: {
                has_children:true
                id:2
                level:1
                name:"智能手机"
                parentId:1

            }
            
    
        }

        result [{has_children:true
                id:1
                level:0
                    name:"手机"
                parentId:null
            },
                {
                has_children:true
                id:2
                level:1
                name:"智能手机"
                parentId:1

            },{
                has_children:false
                id:3
                level:2
                name:"高端手机"
                parentId:2
            },]
    */

    //搜索：分类
    const getCategoryName = (categoryId, result = []) => {
        //查找对应的数据（对象）
        const category = categoryMap.value[categoryId]
        //添加到结果result中
        if (category) {
            result.unshift(category);
            //说明还有父节点，继续递归查找
            if (category.parentId) {
                getCategoryName(category.parentId, result);
            }

        }
        return result;
    }

    return {
        categoryTree,
        loading,
        categoryList,
        categoryMap,
        getCategoryName
    }


}